"use client"

import React, { useState, useEffect } from 'react'
import { AdminLayout } from '@/components/layout/admin-layout'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Modal } from '@/components/ui/modal'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Briefcase,
  Plus,
  Search,
  Filter,
  RefreshCw,
  Eye,
  Edit,
  Download,
  User,
  Calendar,
  Building,
  Trash2,
  X
} from 'lucide-react'
import { adminAPI, type BusinessPlan } from '@/lib/api'
import { formatDateTime } from '@/lib/utils'
import { CompletePagination } from '@/components/ui/pagination'
import { useToast } from '@/components/ui/toast'
import { useConfirm } from '@/components/ui/confirm'

export default function BusinessPlansPage() {
  const [plans, setPlans] = useState<BusinessPlan[]>([])
  const [loading, setLoading] = useState(true)
  const toast = useToast()
  const confirm = useConfirm()
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<'all' | 'draft' | 'completed' | 'reviewed'>('all')
  const [industryFilter, setIndustryFilter] = useState<string>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 创建模板模态框状态
  const [showCreateTemplateModal, setShowCreateTemplateModal] = useState(false)
  const [createTemplateForm, setCreateTemplateForm] = useState({
    name: '',
    description: '',
    industry: '科技',
    stage: '创意阶段',
    sections: [
      { title: '执行摘要', description: '简要介绍您的商业理念、目标市场和关键成功因素' },
      { title: '市场分析', description: '分析目标市场规模、竞争环境和市场机会' },
      { title: '产品服务', description: '详细描述您的产品或服务特点和优势' },
      { title: '营销策略', description: '制定市场推广和销售策略' },
      { title: '财务规划', description: '预测收入、成本和盈利状况' }
    ]
  })
  const [submitting, setSubmitting] = useState(false)

  // 查看和编辑商业计划模态框状态
  const [showViewModal, setShowViewModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [selectedPlan, setSelectedPlan] = useState<BusinessPlan | null>(null)
  const [editPlanForm, setEditPlanForm] = useState({
    title: '',
    description: '',
    industry: '',
    stage: '',
    status: 'draft' as 'draft' | 'completed' | 'reviewed'
  })

  useEffect(() => {
    const loadPlans = async () => {
      try {
        const plansData = await adminAPI.getAllBusinessPlans()
        setPlans(plansData)
      } catch (error) {
        console.error('加载商业计划书失败:', error)
      } finally {
        setLoading(false)
      }
    }

    loadPlans()
  }, [])

  const filteredPlans = plans.filter(plan => {
    const matchesSearch = 
      plan.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      plan.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      plan.authorName.toLowerCase().includes(searchTerm.toLowerCase())

    const matchesStatus = 
      statusFilter === 'all' || plan.status === statusFilter

    const matchesIndustry =
      industryFilter === 'all' || plan.industry === industryFilter

    return matchesSearch && matchesStatus && matchesIndustry
  })

  // 分页计算
  const totalItems = filteredPlans.length
  const totalPages = Math.ceil(totalItems / pageSize)
  const startIndex = (currentPage - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedPlans = filteredPlans.slice(startIndex, endIndex)

  // 重置搜索或筛选时回到第一页
  useEffect(() => {
    setCurrentPage(1)
  }, [searchTerm, statusFilter, industryFilter])

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  const handlePageSizeChange = (size: number) => {
    setPageSize(size)
    setCurrentPage(1)
  }

  const industries = [...new Set(plans.map(plan => plan.industry))]

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <Badge className="bg-green-100 text-green-800">已完成</Badge>
      case 'draft':
        return <Badge className="bg-yellow-100 text-yellow-800">草稿</Badge>
      case 'reviewed':
        return <Badge className="bg-blue-100 text-blue-800">已审核</Badge>
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  const getStageBadge = (stage: string) => {
    const stageMap: Record<string, { color: string }> = {
      '创意阶段': { color: 'bg-purple-100 text-purple-800' },
      '初创阶段': { color: 'bg-blue-100 text-blue-800' },
      '成长阶段': { color: 'bg-green-100 text-green-800' },
    }
    const config = stageMap[stage] || { color: 'bg-gray-100 text-gray-800' }
    return <Badge className={config.color}>{stage}</Badge>
  }

  // 处理商业计划操作（查看、编辑、导出、删除）
  const handlePlanAction = async (action: string, planId: string) => {
    try {
      if (action === '查看') {
        const plan = await adminAPI.getBusinessPlanById(planId)
        setSelectedPlan(plan)
        setShowViewModal(true)
      } else if (action === '编辑') {
        const plan = await adminAPI.getBusinessPlanById(planId)
        setSelectedPlan(plan)
        setEditPlanForm({
          title: plan.title,
          description: plan.description,
          industry: plan.industry,
          stage: plan.stage,
          status: plan.status
        })
        setShowEditModal(true)
      } else if (action === '导出') {
        // 这里可以实现PDF导出功能，暂时先提示用户
        toast.info(`正在导出 "${planId}" 的PDF文档，请稍等...`)
        // TODO: 实现真正的PDF导出功能
      } else if (action === '删除') {
        const confirmed = await confirm({
          title: '确认删除商业计划书',
          message: '确认删除这个商业计划书吗？此操作不可恢复！',
          type: 'danger',
          confirmText: '删除',
          cancelText: '取消'
        })
        
        if (confirmed) {
          await adminAPI.deleteBusinessPlan(planId)
          // 重新加载计划书列表
          const plansData = await adminAPI.getAllBusinessPlans()
          setPlans(plansData)
          toast.success('商业计划书删除成功！')
        }
      }
    } catch (error) {
      console.error(`${action}商业计划书失败:`, error)
      toast.error(`${action}商业计划书失败，请重试`)
    }
  }

  // 处理编辑商业计划表单变化
  const handleEditPlanFormChange = (field: string, value: string) => {
    setEditPlanForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 重置编辑表单
  const resetEditPlanForm = () => {
    setEditPlanForm({
      title: '',
      description: '',
      industry: '',
      stage: '',
      status: 'draft'
    })
  }

  // 处理编辑商业计划
  const handleEditPlan = async () => {
    if (!editPlanForm.title || !editPlanForm.description) {
      toast.warning('请填写必填字段：标题、描述')
      return
    }

    if (!selectedPlan) return

    setSubmitting(true)
    try {
      // 调用API更新商业计划
      await adminAPI.updateBusinessPlan(selectedPlan.id, editPlanForm)
      
      // 重新加载商业计划列表
      const plansData = await adminAPI.getAllBusinessPlans()
      setPlans(plansData)
      
      // 关闭模态框并重置表单
      setShowEditModal(false)
      resetEditPlanForm()
      setSelectedPlan(null)
      
      toast.success('商业计划书更新成功！')
    } catch (error) {
      console.error('更新商业计划书失败:', error)
      toast.error('更新商业计划书失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  // 处理创建模板表单变化
  const handleTemplateFormChange = (field: string, value: string) => {
    setCreateTemplateForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 处理模板章节变化
  const handleSectionChange = (index: number, field: string, value: string) => {
    setCreateTemplateForm(prev => ({
      ...prev,
      sections: prev.sections.map((section, i) => 
        i === index ? { ...section, [field]: value } : section
      )
    }))
  }

  // 添加新章节
  const addSection = () => {
    setCreateTemplateForm(prev => ({
      ...prev,
      sections: [...prev.sections, { title: '', description: '' }]
    }))
  }

  // 删除章节
  const removeSection = (index: number) => {
    if (createTemplateForm.sections.length > 1) {
      setCreateTemplateForm(prev => ({
        ...prev,
        sections: prev.sections.filter((_, i) => i !== index)
      }))
    }
  }

  // 重置模板表单
  const resetTemplateForm = () => {
    setCreateTemplateForm({
      name: '',
      description: '',
      industry: '科技',
      stage: '创意阶段',
      sections: [
        { title: '执行摘要', description: '简要介绍您的商业理念、目标市场和关键成功因素' },
        { title: '市场分析', description: '分析目标市场规模、竞争环境和市场机会' },
        { title: '产品服务', description: '详细描述您的产品或服务特点和优势' },
        { title: '营销策略', description: '制定市场推广和销售策略' },
        { title: '财务规划', description: '预测收入、成本和盈利状况' }
      ]
    })
  }

  // 处理创建模板
  const handleCreateTemplate = async () => {
    if (!createTemplateForm.name || !createTemplateForm.description) {
      toast.warning('请填写必填字段：模板名称、模板描述')
      return
    }

    if (createTemplateForm.sections.some(section => !section.title)) {
      toast.warning('请填写所有章节的标题')
      return
    }

    setSubmitting(true)
    try {
      // 准备模板数据，确保包含userId字段
      const templateData = {
        ...createTemplateForm,
        userId: 0, // 设置为0表示系统模板
        title: createTemplateForm.name,
        companyName: '系统模板',
        planData: JSON.stringify({ sections: createTemplateForm.sections })
      }
      
      // 调用API创建模板
      await adminAPI.createBusinessPlanTemplate(templateData)
      
      // 重新加载商业计划列表以显示新创建的模板
      const plansData = await adminAPI.getAllBusinessPlans()
      setPlans(plansData)
      
      // 关闭模态框并重置表单
      setShowCreateTemplateModal(false)
      resetTemplateForm()
      
      toast.success('商业计划书模板创建成功！')
    } catch (error) {
      console.error('创建模板失败:', error)
      toast.error('创建模板失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <AdminLayout>
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-gray-900">商业计划书管理</h1>
          </div>
          <div className="text-center py-12">加载中...</div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">商业计划书管理</h1>
            <p className="text-gray-600">管理和审核用户提交的商业计划书</p>
          </div>
          <Button onClick={() => setShowCreateTemplateModal(true)}>
            <Plus className="h-4 w-4 mr-2" />
            创建模板
          </Button>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">计划书总数</p>
                  <p className="text-2xl font-bold text-gray-900">{plans.length}</p>
                </div>
                <Briefcase className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">已完成</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {plans.filter(p => p.status === 'completed').length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                  <Briefcase className="h-5 w-5 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">待审核</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {plans.filter(p => p.status === 'completed' || p.status === 'reviewed').length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-amber-100 rounded-full flex items-center justify-center">
                  <Briefcase className="h-5 w-5 text-amber-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">草稿</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {plans.filter(p => p.status === 'draft').length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                  <Briefcase className="h-5 w-5 text-gray-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters and Search */}
        <Card>
          <CardContent className="p-6">
            <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
              <div className="flex flex-1 gap-4">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <input
                    type="text"
                    placeholder="搜索计划书..."
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
                <select
                  className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value as any)}
                >
                  <option value="all">全部状态</option>
                  <option value="completed">已完成</option>
                  <option value="draft">草稿</option>
                  <option value="reviewed">已审核</option>
                </select>
                <select
                  className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={industryFilter}
                  onChange={(e) => setIndustryFilter(e.target.value)}
                >
                  <option value="all">全部行业</option>
                  {industries.map(industry => (
                    <option key={industry} value={industry}>{industry}</option>
                  ))}
                </select>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <Filter className="h-4 w-4 mr-2" />
                  高级筛选
                </Button>
                <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
                  <RefreshCw className="h-4 w-4 mr-2" />
                  刷新
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Business Plans Table */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Briefcase className="h-5 w-5" />
                <span>商业计划书列表 ({filteredPlans.length})</span>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>计划书信息</TableHead>
                  <TableHead>行业/阶段</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建者</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>更新时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedPlans.length > 0 ? (
                  paginatedPlans.map((plan) => (
                    <TableRow key={plan.id}>
                      <TableCell>
                        <div className="max-w-md">
                          <h4 className="font-medium text-gray-900 mb-1">{plan.title}</h4>
                          <p className="text-sm text-gray-500 line-clamp-2">{plan.description}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-2">
                          <Badge className="bg-blue-100 text-blue-800">
                            <Building className="h-3 w-3 mr-1" />
                            {plan.industry}
                          </Badge>
                          <div>
                            {getStageBadge(plan.stage)}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {getStatusBadge(plan.status)}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <User className="h-4 w-4 text-gray-400" />
                          <div>
                            <div className="text-sm font-medium text-gray-900">{plan.authorName}</div>
                            <div className="text-xs text-gray-500">ID: {plan.authorId}</div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          <div className="flex items-center space-x-1 mb-1">
                            <Calendar className="h-3 w-3" />
                            <span>创建</span>
                          </div>
                          <div>{formatDateTime(plan.createdAt)}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          <div className="flex items-center space-x-1 mb-1">
                            <Calendar className="h-3 w-3" />
                            <span>更新</span>
                          </div>
                          <div>{formatDateTime(plan.updatedAt)}</div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handlePlanAction('查看', plan.id)}
                            title="查看详情"
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handlePlanAction('编辑', plan.id)}
                            title="编辑"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handlePlanAction('导出', plan.id)}
                            title="导出PDF"
                          >
                            <Download className="h-4 w-4 text-green-600" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handlePlanAction('删除', plan.id)}
                            title="删除"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      <div className="text-gray-500">
                        {searchTerm || statusFilter !== 'all' || industryFilter !== 'all' 
                          ? '没有找到匹配的计划书' 
                          : '暂无计划书数据'
                        }
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Pagination */}
        {totalItems > 0 && (
          <Card>
            <CardContent className="p-6">
              <CompletePagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalItems}
                pageSize={pageSize}
                onPageChange={handlePageChange}
                onPageSizeChange={handlePageSizeChange}
                pageSizeOptions={[5, 10, 20, 50]}
              />
            </CardContent>
          </Card>
        )}

        {/* Create Template Modal */}
        <Modal
          isOpen={showCreateTemplateModal}
          onClose={() => {
            setShowCreateTemplateModal(false)
            resetTemplateForm()
          }}
          title="创建商业计划书模板"
          size="xl"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowCreateTemplateModal(false)
                  resetTemplateForm()
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleCreateTemplate}
                disabled={submitting}
              >
                {submitting ? '创建中...' : '创建模板'}
              </Button>
            </div>
          }
        >
          <div className="space-y-6 max-h-96 overflow-y-auto">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">基本信息</h3>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  模板名称 <span className="text-red-500">*</span>
                </label>
                <Input
                  value={createTemplateForm.name}
                  onChange={(e) => handleTemplateFormChange('name', e.target.value)}
                  placeholder="请输入模板名称"
                  disabled={submitting}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  模板描述 <span className="text-red-500">*</span>
                </label>
                <textarea
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  rows={3}
                  value={createTemplateForm.description}
                  onChange={(e) => handleTemplateFormChange('description', e.target.value)}
                  placeholder="请输入模板描述"
                  disabled={submitting}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    适用行业
                  </label>
                  <select
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                    value={createTemplateForm.industry}
                    onChange={(e) => handleTemplateFormChange('industry', e.target.value)}
                    disabled={submitting}
                  >
                    <option value="科技">科技</option>
                    <option value="金融">金融</option>
                    <option value="教育">教育</option>
                    <option value="医疗">医疗</option>
                    <option value="电商">电商</option>
                    <option value="制造业">制造业</option>
                    <option value="服务业">服务业</option>
                    <option value="其他">其他</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    适用阶段
                  </label>
                  <select
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                    value={createTemplateForm.stage}
                    onChange={(e) => handleTemplateFormChange('stage', e.target.value)}
                    disabled={submitting}
                  >
                    <option value="创意阶段">创意阶段</option>
                    <option value="初创阶段">初创阶段</option>
                    <option value="成长阶段">成长阶段</option>
                  </select>
                </div>
              </div>
            </div>

            {/* 模板章节 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">模板章节</h3>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={addSection}
                  disabled={submitting}
                >
                  <Plus className="h-4 w-4 mr-1" />
                  添加章节
                </Button>
              </div>

              {createTemplateForm.sections.map((section, index) => (
                <div key={index} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-sm font-medium text-gray-700">章节 {index + 1}</span>
                    {createTemplateForm.sections.length > 1 && (
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => removeSection(index)}
                        disabled={submitting}
                      >
                        <Trash2 className="h-4 w-4 text-red-600" />
                      </Button>
                    )}
                  </div>
                  
                  <div className="space-y-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        章节标题 <span className="text-red-500">*</span>
                      </label>
                      <Input
                        value={section.title}
                        onChange={(e) => handleSectionChange(index, 'title', e.target.value)}
                        placeholder="请输入章节标题"
                        disabled={submitting}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        章节说明
                      </label>
                      <textarea
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                        rows={2}
                        value={section.description}
                        onChange={(e) => handleSectionChange(index, 'description', e.target.value)}
                        placeholder="请输入章节说明"
                        disabled={submitting}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Modal>

        {/* View Business Plan Modal */}
        <Modal
          isOpen={showViewModal}
          onClose={() => {
            setShowViewModal(false)
            setSelectedPlan(null)
          }}
          title="查看商业计划书详情"
          size="xl"
          footer={
            <div className="flex justify-end">
              <Button onClick={() => setShowViewModal(false)}>关闭</Button>
            </div>
          }
        >
          {selectedPlan && (
            <div className="space-y-4 max-h-96 overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">计划书ID</label>
                  <div className="text-sm text-gray-900">{selectedPlan.id}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">创建者</label>
                  <div className="text-sm text-gray-900">{selectedPlan.authorName} (ID: {selectedPlan.authorId})</div>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">标题</label>
                <div className="text-base font-medium text-gray-900">{selectedPlan.title}</div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">描述</label>
                <div className="text-sm text-gray-700 border border-gray-200 rounded p-3 bg-gray-50">
                  {selectedPlan.description}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">行业</label>
                  <div className="text-sm text-gray-900">{selectedPlan.industry}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">发展阶段</label>
                  <div className="text-sm">{getStageBadge(selectedPlan.stage)}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                  <div className="text-sm">{getStatusBadge(selectedPlan.status)}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                  <div className="text-sm text-gray-900">{formatDateTime(selectedPlan.createdAt)}</div>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">最后更新</label>
                <div className="text-sm text-gray-900">{formatDateTime(selectedPlan.updatedAt)}</div>
              </div>
            </div>
          )}
        </Modal>

        {/* Edit Business Plan Modal */}
        <Modal
          isOpen={showEditModal}
          onClose={() => {
            setShowEditModal(false)
            resetEditPlanForm()
            setSelectedPlan(null)
          }}
          title="编辑商业计划书"
          size="xl"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowEditModal(false)
                  resetEditPlanForm()
                  setSelectedPlan(null)
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleEditPlan}
                disabled={submitting}
              >
                {submitting ? '保存中...' : '保存更改'}
              </Button>
            </div>
          }
        >
          <div className="space-y-4 max-h-96 overflow-y-auto">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                标题 <span className="text-red-500">*</span>
              </label>
              <Input
                value={editPlanForm.title}
                onChange={(e) => handleEditPlanFormChange('title', e.target.value)}
                placeholder="请输入计划书标题"
                disabled={submitting}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                描述 <span className="text-red-500">*</span>
              </label>
              <textarea
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                rows={4}
                value={editPlanForm.description}
                onChange={(e) => handleEditPlanFormChange('description', e.target.value)}
                placeholder="请输入计划书描述"
                disabled={submitting}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  行业
                </label>
                <select
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={editPlanForm.industry}
                  onChange={(e) => handleEditPlanFormChange('industry', e.target.value)}
                  disabled={submitting}
                >
                  <option value="科技">科技</option>
                  <option value="金融">金融</option>
                  <option value="教育">教育</option>
                  <option value="医疗">医疗</option>
                  <option value="电商">电商</option>
                  <option value="制造业">制造业</option>
                  <option value="服务业">服务业</option>
                  <option value="其他">其他</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  发展阶段
                </label>
                <select
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={editPlanForm.stage}
                  onChange={(e) => handleEditPlanFormChange('stage', e.target.value)}
                  disabled={submitting}
                >
                  <option value="创意阶段">创意阶段</option>
                  <option value="初创阶段">初创阶段</option>
                  <option value="成长阶段">成长阶段</option>
                </select>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                状态
              </label>
              <select
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                value={editPlanForm.status}
                onChange={(e) => handleEditPlanFormChange('status', e.target.value as 'draft' | 'completed' | 'reviewed')}
                disabled={submitting}
              >
                <option value="draft">草稿</option>
                <option value="completed">已完成</option>
                <option value="reviewed">已审核</option>
              </select>
            </div>
          </div>
        </Modal>
      </div>
    </AdminLayout>
  )
}